<template>
  <div class="notification-list">
    <div class="notification-header">
      <h3>通知</h3>
      <a @click="markAllAsRead" v-if="notifications.length > 0">全部标为已读</a>
    </div>
    
    <a-spin :spinning="loading">
      <a-empty v-if="notifications.length === 0" description="暂无通知" />
      
      <div v-else class="notification-items">
        <div 
          v-for="notification in notifications" 
          :key="notification.id"
          class="notification-item"
          :class="{ 'unread': notification.status === 0 }"
          @click="viewNotification(notification)"
        >
          <div class="notification-icon" :class="getNotificationIconClass(notification.type)">
            <template v-if="notification.type === 'ARTICLE_COMMENT'">
              <CommentOutlined />
            </template>
            <template v-else-if="notification.type === 'COMMENT_REPLY'">
              <MessageOutlined />
            </template>
            <template v-else-if="notification.type === 'ARTICLE_LIKE'">
              <LikeOutlined />
            </template>
          </div>
          
          <div class="notification-content">
            <div class="notification-message">
              <strong>{{ getInitiatorName(notification.initiatorId) }}</strong>
              {{ getNotificationMessage(notification) }}
            </div>
            <div class="notification-time">{{ formatTime(notification.createTime) }}</div>
          </div>
        </div>
      </div>
      
      <div class="notification-footer" v-if="hasMore">
        <a-button @click="loadMore" :loading="loadingMore">加载更多</a-button>
      </div>
    </a-spin>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { CommentOutlined, MessageOutlined, LikeOutlined } from '@ant-design/icons-vue';
import { getNotifications, markAsRead, markAllNotificationsAsRead } from '@/api/notification';

const router = useRouter();
const loading = ref(false);
const loadingMore = ref(false);
const notifications = ref([]);
const page = ref(1);
const hasMore = ref(true);
const userCache = ref({});

onMounted(async () => {
  await fetchNotifications();
});

const fetchNotifications = async () => {
  loading.value = true;
  try {
    const res = await getNotifications(page.value, 10);
    notifications.value = res.records || [];
    hasMore.value = res.total > notifications.value.length;
  } catch (error) {
    console.error('获取通知失败:', error);
  } finally {
    loading.value = false;
  }
};

const loadMore = async () => {
  if (loadingMore.value) return;
  
  loadingMore.value = true;
  try {
    page.value++;
    const res = await getNotifications(page.value, 10);
    
    if (res.records && res.records.length > 0) {
      notifications.value = [...notifications.value, ...res.records];
    }
    
    hasMore.value = res.total > notifications.value.length;
  } catch (error) {
    console.error('加载更多通知失败:', error);
    message.error('加载更多失败');
  } finally {
    loadingMore.value = false;
  }
};

const getNotificationIconClass = (type) => {
  switch (type) {
    case 'ARTICLE_COMMENT': return 'comment-icon';
    case 'COMMENT_REPLY': return 'reply-icon';
    case 'ARTICLE_LIKE': return 'like-icon';
    default: return '';
  }
};

const getNotificationMessage = (notification) => {
  switch (notification.type) {
    case 'ARTICLE_COMMENT': return '评论了你的文章';
    case 'COMMENT_REPLY': return '回复了你的评论';
    case 'ARTICLE_LIKE': return '赞了你的文章';
    default: return notification.content;
  }
};

const getInitiatorName = (initiatorId) => {
  return userCache.value[initiatorId] || `用户${initiatorId}`;
};

const formatTime = (dateString) => {
  if (!dateString) return '';
  
  const now = new Date();
  const date = new Date(dateString);
  const diff = now.getTime() - date.getTime();
  
  // 小于一分钟
  if (diff < 60 * 1000) {
    return '刚刚';
  }
  
  // 小于一小时
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`;
  }
  
  // 小于一天
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
  }
  
  // 小于一周
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`;
  }
  
  // 其他情况显示完整日期
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  
  return `${year}-${month}-${day}`;
};

const viewNotification = async (notification) => {
  try {
    // 如果是未读通知，标记为已读
    if (notification.status === 0) {
      try {
        await markAsRead(notification.id);
        notification.status = 1;
        emit('notification-read');
      } catch (error) {
        console.error('标记已读失败:', error);
      }
    }
    
    // 根据通知类型跳转到相应页面
    if (notification.articleId) {
      // 构建URL，包含评论ID信息
      let targetUrl = `/article/${notification.articleId}`;
      
      // 对于评论相关通知，添加评论ID查询参数
      if (notification.commentId && 
         (notification.type === 'ARTICLE_COMMENT' || notification.type === 'COMMENT_REPLY')) {
        targetUrl += `?commentId=${notification.commentId}`;
      }
      
      console.log('跳转到:', targetUrl);
      
      // 关闭下拉菜单
      emit('close-dropdown');
      
      // 使用replace确保页面刷新，重新加载组件
      router.replace(targetUrl);
    }
  } catch (error) {
    console.error('处理通知点击失败:', error);
    message.error('处理失败，请重试');
  }
};

const markAllAsRead = async () => {
  try {
    await markAllNotificationsAsRead();
    message.success('全部标为已读');
    
    // 更新本地通知状态
    notifications.value.forEach(notification => {
      notification.status = 1;
    });
  } catch (error) {
    console.error('标记全部已读失败:', error);
    message.error('操作失败');
  }
};

// 添加emit定义
const emit = defineEmits(['notification-read', 'close-dropdown']);
</script>

<style scoped>
.notification-list {
  min-width: 300px;
  max-width: 400px;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.notification-header h3 {
  margin: 0;
  font-size: 16px;
}

.notification-items {
  max-height: 400px;
  overflow-y: auto;
}

.notification-item {
  display: flex;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.notification-item:hover {
  background-color: #f5f5f5;
}

.notification-item.unread {
  background-color: #e6f7ff;
}

.notification-icon {
  flex-shrink: 0;
  margin-right: 12px;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 18px;
}

.comment-icon {
  background-color: #1890ff;
}

.reply-icon {
  background-color: #52c41a;
}

.like-icon {
  background-color: #f5222d;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-message {
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.notification-time {
  font-size: 12px;
  color: #999;
}

.notification-footer {
  padding: 12px;
  text-align: center;
}
</style> 